package com.kedacom.ctsp.authz.security.provider;

import com.alibaba.fastjson.JSONObject;
import com.kedacom.ctsp.authz.AuthenticationService;
import com.kedacom.ctsp.logging.AccessLoggerEvent;
import com.kedacom.ctsp.logging.AccessLoggerInfo;
import com.kedacom.ctsp.starter.springboot.CorsProperties;
import com.kedacom.ctsp.web.controller.message.ResponseMessage;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.http.MediaType;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.web.authentication.logout.LogoutSuccessHandler;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @author sunchenjie
 * @date 2017/12/12 0012
 */
@Slf4j
public class RestLogoutSuccessHandler implements LogoutSuccessHandler {

    @Autowired(required = false)
    private CorsProperties corsProperties;

    @Autowired(required = false)
    private RedisTokenManager tokenManager;

    @Autowired
    private AuthenticationService authenticationService;

    @Autowired
    protected ApplicationContext context;

    @Override
    public void onLogoutSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException {

        response.setContentType(MediaType.APPLICATION_JSON_UTF8_VALUE);
        response.setCharacterEncoding("UTF-8");

        // 删除token
        //判断是否启用redis
        if (tokenManager != null) {
            String clientToken = request.getHeader("token");
            tokenManager.logout(clientToken);
        }
        if (authentication != null && authentication.getPrincipal() != null
                && authentication.getPrincipal() instanceof UserDetails) {

            UserDetails userDetails = (UserDetails) authentication.getPrincipal();
            if (userDetails != null) {
                // 清空缓存
                authenticationService.logout(userDetails.getUsername());
                //手动发布登出事件
                AccessLoggerInfo info = RestLogoutAccessLoggerSupport.createLogger(request, response, authentication);
                context.publishEvent(new AccessLoggerEvent(info));
            }
        }


        ResponseMessage<Object> ok = ResponseMessage.ok();
        response.getWriter().println(JSONObject.toJSON(ok));
    }
}
